/**
 * @author:linjiye
 * @date: 2025/1/2
 * @desc:
 **/

import {Animated, Easing, StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import React, {useEffect, useRef, useState} from 'react'
import TabCard from "@/components/TabCard";
import PageFormBtn from "@/components/PageFormBtn";
import PageScrollView from "@/components/PageScrollView";
import FcButton from "@/components/FcButton";
import {useSelector} from "react-redux";
import {strSimilar} from "@/utils";
import {useReduceSimilarityMutation} from "@/store/api/aiOriginality/aiOriginalityApi";
import useApiOfSSE from "@/hooks/useApiOfSSE";
import useGetStorage from "@/hooks/useGetStorage";
import {Toast} from "@ant-design/react-native";
import NoData from "@/components/NoData";
import FileTabBtn from "@/components/FileTabBtn";

type Props = {}

const textComparison = (props: Props) => {
    const [oldList, setOldList] = useState([])
    const [list, setList] = useState([])
    const [selectedItems, setSelectedItems] = useState([]);
    const [fadeAnim] = useState(new Animated.Value(0));  // 初始透明度为0
    const [isExpanded, setIsExpanded] = useState(false); // 文案展开状态
    const [txt, setTxt] = useState('');
    const [compareList, setCompareList] = useState([]);
    const [carouselIndex, setCarouselIndex] = useState(0);

    const [reduceSimilarFun] = useReduceSimilarityMutation()

    const p = useSelector(state => state.aiOriginality.result)
    useEffect(() => {
        console.log(p);
        if (p) {
            // addIndex(p)

            let newList = []
            p.forEach((item, index) => {
                newList.push({
                    ...item,
                    //  childList: [],
                    id: index + 1,
                    //  pId: 0,
                    comNum: 0,
                    tag: index,
                    tabName: index === 0 ? '原文' : `第${index}篇`,
                })
            })
            setList(newList)

        }
    }, [p]);

    useEffect(() => {
        if (oldList.length) {
            handleOldList(oldList)
        }
    }, [oldList]);

    function handleClickSub() {
        let i = carouselIndex - 1
        setCarouselIndex(i)
    }

    function handleClickAdd() {
        let i = carouselIndex + 1
        setCarouselIndex(i)
    }

    function handleOldList() {

    }

    function addIndex(data) {
        let l = data || [...list]
        let arr = []
        l.forEach((item, index) => {
            let indexStr = item.data2 ? item.data2.indexStr + '-1' : index
            arr.push({
                id: index,
                content: item.content,
                indexStr,
                tabName: index === 0 ? '原文' : `第${indexStr}篇`,
            })
        })
        setList(arr)
    }

    const expandText = () => {
        setIsExpanded(true);
        Animated.timing(
            fadeAnim,
            {
                toValue: 1,
                duration: 300,
                easing: Easing.linear,
                useNativeDriver: true,
            }
        ).start();
    };

    const collapseText = () => {
        setIsExpanded(false);
        Animated.timing(
            fadeAnim,
            {
                toValue: 0,
                duration: 300,
                easing: Easing.linear,
                useNativeDriver: true,
            }
        ).start();
    };

    function handleSelectItem(item, type) {
        if (selectedItems.find(i => i.id === item.id)) {
            setSelectedItems(selectedItems.filter(i => i.id !== item.id));
        } else {
            setSelectedItems([...selectedItems, item]);
        }
    }

    function isSelected(id) {
        return selectedItems.find(item => item.id === id)
    }

    function handleComparison() {
        compareData(selectedItems);
    }

    function compareData(data) {
        data.sort((a, b) => a.id - b.id);
        const n = data.length;
        const list = []
        for (let i = 0; i < n; i++) {
            for (let j = i + 1; j < n; j++) {
                let d = strSimilar(data[i].content, data[j].content, 2)
                const obj = {
                    title: `${data[i].tabName} : ${data[j].tabName}`,
                    similar: d * 1,
                    data1: data[i],
                    data2: data[j]
                }
                list.push(obj)
            }
        }
        setCompareList(list)
    }

    async function ReduceSimilar(item: any) {
        // useApiOfSSE({
        //     url: 'mm/aicreation/reduce_similarity',
        //     payload: {
        //         stream: true,
        //         reqIndex: 0,
        //         content: item.data2.content
        //     }
        // }).then((resData) => {
        //     resData.addEventListener('message', (e) => {
        //
        //         let res = JSON.parse(e.data)
        //         if (res.status == 'success') {
        //             let txt = res.text.replace(/(<br\/>)|(<br)/g, '');
        // let l = [...list]
        //             // l[index - 1].content = txt
        //             // setList(l)
        //             setTxt(txt)
        //
        //             if(res.stop){
        //                 console.log(obj);
        //                 obj.content = txt
        //                 // l[item.dataIndex2+1].content = txt
        //                 console.log(newList,'-----');
        //                 setList(newList)
        //                 handleSelectItem(obj,1)
        //             }
        //         } else {
        //             resData.close();
        //         }
        //     })
        // })
        Toast.show({
            icon: 'loading',
            content: '数据正在处理中...',
            duration: 0,
            mask: false,
        })
        await useGetStorage('token').then(async (token) => {
            try {
                const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}mm/aicreation/reduce_similarity`, {
                    method: 'POST',
                    headers: {
                        'content-type': 'application/json',
                        'x-access-token': token,
                    },
                    body: JSON.stringify({
                        stream: true,
                        reqIndex: 0,
                        content: item.data2.content
                    })
                });
                const blob = await response.blob();
                const reader = new FileReader();

                reader.onload = (event) => {
                    const result = event.target.result;
                    // 按行分割流式数据
                    const lines = result.split('\n');
                    lines.forEach((line) => {
                        if (line) {
                            // console.log(line);
                            let newLine = `${line.replace('data:', '')}`;
                            // 在这里处理流式数据
                            let res = JSON.parse(newLine)
                            let text = ''
                            let newList = [...list]
                            if (res.status == 'success') {
                                text = res.text.replace(/(<br\/>)|(<br)/g, '');
                                newList?.map((i, index) => {
                                    if (i.id === item.data2.id) {
                                        i.content = text
                                    }
                                })
                                setList(newList)
                            }
                            if (res.stop) {
                                newList?.map((i, index) => {
                                    if (i.id === item.data2.id) {
                                        i.comNum += 1
                                        i.tag = item.data2.tag + '-1'
                                        i.tabName = `第${i.tag}篇`
                                    }
                                })
                                setList(newList)
                                handleComparison()
                            }
                        }
                    });
                    Toast.removeAll()
                };

                reader.onerror = (error) => {
                    console.error('Error reading blob:', error);
                    Toast.removeAll()
                };

                reader.readAsText(blob);
            } catch (error) {
                console.log('Error fetching stream:', error);
                Toast.removeAll()
            }
        })
    }

    return (
        <PageScrollView
            isHaveHeader
            isTransparentTab
        >
            <View style={styles.condition_wrap}>
                <View style={styles.hint}>
                    <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: '#FAAD14'}}>&#xe638;</Text>
                    <Text style={styles.hint_txt}>最少选择2篇文案进行自由对比</Text>
                </View>
                <View style={styles.list_wrap}>
                    {list.map((item, index) => (
                        <TouchableOpacity style={styles.list_item_wrap} onPress={() => handleSelectItem(item)}
                                          key={index}>
                            <Text
                                style={[styles.list_item, isSelected(item.id) && styles.list_active]} numberOfLines={1}
                                ellipsizeMode="tail">{item.tabName}</Text>
                        </TouchableOpacity>
                    ))}
                </View>
                <View style={styles.comparison_btn}>
                    <FcButton
                        disable={selectedItems.length < 2}
                        onClick={() => handleComparison()}
                        type='BjJB'
                        colors={['#6989FF', '#C65EFD']}
                        style={{width: '100%', height: 40, justifyContent: 'center'}}
                        itemStyle={{borderRadius: 8, fontSize: 15}}
                        textName='开始对比'/>
                </View>
                <View style={styles.txt_wrap}>
                    <View style={styles.txt_wrap_btn}>
                        <Text style={styles.txt_index}>第{carouselIndex + 1}篇 默认式</Text>
                        <FileTabBtn index={carouselIndex} len={list.length} onClickSub={handleClickSub}
                                    onClickAdd={handleClickAdd}/>
                    </View>
                    <>
                        {list[carouselIndex]?.content &&
                            <Animated.Text style={[styles.content, {opacity: !isExpanded ? 1 : fadeAnim}]}>
                                {isExpanded ? list[carouselIndex]?.content : `${list[carouselIndex]?.content.substring(0, 20)}...`}
                            </Animated.Text>
                        }
                    </>
                </View>
                <TouchableOpacity onPress={() => isExpanded ? collapseText() : expandText()}>
                    <Text style={styles.show_more}>{isExpanded ? '收起文案' : '显示全部文案'}</Text>
                </TouchableOpacity>
            </View>
            <View style={styles.result_wrap}>
                <Text style={styles.result_len}>文案相似度对比结果<Text
                    style={{color: 'rgba(0, 0, 0, 0.3)'}}>（共{compareList.length}篇）</Text>：</Text>

                {compareList?.length <= 0 && <NoData hintText='暂无文案对比结果'/>}

                {compareList.map((item, index) =>
                    <View style={styles.result_list} key={index}>
                        <Text style={styles.result_title} numberOfLines={1} ellipsizeMode="tail">{item.title}</Text>
                        <View style={{flex: 1}}>
                            <View style={[styles.result_bfb_box,{backgroundColor: item.similar >= 30 ? 'rgba(250, 81, 81, 0.1)':'rgba(7, 193, 96, 0.1)'}]}>
                                <Text style={[styles.result_bfb, {color: item.similar >= 30 ? '#EA0000':'#07C160'}]}>{item.similar}%</Text>
                            </View>
                        </View>
                        <View style={styles.result_btn}>
                            {item.similar >= 30 &&
                                <TouchableOpacity style={styles.result_btn} onPress={() => ReduceSimilar(item)}>
                                    <Text style={styles.result_btn_text}>降低相似度</Text>
                                </TouchableOpacity>
                            }
                        </View>
                    </View>
                )}
            </View>
        </PageScrollView>
    )
}

export default textComparison

const styles = StyleSheet.create({
    condition_wrap: {
        backgroundColor: 'white',
        borderRadius: 8,
        overflow: "hidden"
    },
    hint: {
        width: '100%',
        height: 35,
        backgroundColor: 'rgba(255,157,0,0.1)',
        paddingHorizontal: 14,
        flexDirection: "row",
        alignItems: "center",
        marginRight: 2
    },
    hint_txt: {
        fontSize: 12,
        color: '#FF9D00'
    },
    list_wrap: {
        flexDirection: "row",
        flexWrap: "wrap",
        paddingHorizontal: 6,
        marginTop: 2
    },
    list_item_wrap: {
        width: 74,
        height: 34,
        borderRadius: 8,
        backgroundColor: '#F1F2F4',
        display: 'flex',
        alignItems: "center",
        justifyContent: "center",
        marginHorizontal: 6,
        marginTop: 8
    },
    list_item: {
        fontSize: 14,
        color: 'rgba(0, 0, 0, 0.5)',
    },
    list_active: {
        backgroundColor: '#E0EAFF',
        color: '#2856FF'
    },
    comparison_btn: {
        flex: 1,
        marginHorizontal: 14,
        marginTop: 17,
        paddingBottom: 25,
        borderBottomWidth: 1,
        borderBottomColor: 'rgba(0, 0, 0, 0.1)',
        borderStyle: "dashed"
    },
    txt_wrap: {
        paddingHorizontal: 14,
        paddingVertical: 15,
    },
    txt_wrap_btn: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        marginBottom: 15,
    },
    txt_index: {
        fontSize: 12,
        lineHeight: 18,
        color: 'rgba(0, 0, 0, 0.5)',
    },
    content: {
        fontSize: 17,
        lineHeight: 26,
        color: 'rgba(0, 0, 0, 0.9)',
    },
    show_more: {
        fontSize: 15,
        lineHeight: 24,
        color: '#2856FF',
        textAlign: 'center',
        paddingBottom: 17,
    },
    result_wrap: {
        marginTop: -16
    },
    result_len: {
        color: 'rgba(0, 0, 0, 0.9)',
        fontSize: 14,
        lineHeight: 22,
        paddingVertical: 10
    },
    result_list: {
        flexDirection: 'row',
        alignItems: "center",
        backgroundColor: 'white',
        height: 48,
        paddingHorizontal: 16,
        marginBottom: 8,
        borderRadius: 8
    },
    result_title: {
        flex: 1
    },
    result_bfb_box: {
        width: 64,
        height: 22,
        borderRadius: 25,
        display: "flex",
        alignItems: "center",
        justifyContent: 'center',
        marginHorizontal: 'auto',
    },
    result_bfb: {
        fontSize: 14
    },
    result_btn: {
        flex: 1,
        flexDirection: "row",
        alignItems: "center",
    },
    result_btn_text: {
        textAlign: "right",
        color: '#2856FF',
        fontSize: 15
    }
})